<template>
  <div class="pagination">
    <button :disabled="pageNo <= 1" @click="replacePageNo(pageNo - 1)">
      上一页
    </button>
    <button v-show="pagesArr[0] > 1" @click="replacePageNo(1)">1</button>

    <button v-show="pagesArr[0] > 2">···</button>

    <button
      v-for="item in pagesArr"
      :key="item"
      @click="replacePageNo(item)"
      :class="{ active: pageNo === item }"
    >
      {{ item }}
    </button>

    <button v-show="pagesArr[conutPage - 1] < totalPages - 1">···</button>
    <button
      v-show="pagesArr[conutPage - 1] < totalPages"
      @click="replacePageNo(totalPages)"
    >
      {{ totalPages }}
    </button>
    <button :disabled="pageNo >= totalPages" @click="replacePageNo(pageNo + 1)">
      下一页
    </button>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  props: ['totalPages', 'conutPage', 'pageNo'],
  mounted() {
    console.log(this.totalPages, this.conutPage, this.pageNo)
  },
  computed: {
    pagesArr() {
      let arr = []
      //当传入的页面个数小于最小分页时.就直接遍历总页数生成页码
      if (this.conutPage >= this.totalPages) {
        for (let index = 1; index <= this.totalPages; index++) {
          arr.push(index)
        }
      } else {
        let startpage = this.pageNo - Math.floor(this.conutPage / 2)
        let endpage = this.pageNo + Math.floor(this.conutPage / 2)
        if (startpage <= 1) {
          startpage = 1
          endpage = this.conutPage
        }
        if (endpage >= this.totalPages) {
          endpage = this.totalPages
          startpage = this.totalPages - this.conutPage + 1
        }
        for (let index = startpage; index <= endpage; index++) {
          arr.push(index)
        }
      }
      return arr
    },
  },
  methods: {
    replacePageNo(index) {
      this.$emit('replacePageNo', index)
    },
  },
}
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
